import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yishop/config/Config.dart';
import 'package:flutter_yishop/config/EventBus.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:flutter_yishop/model/AttrStateModel.dart';
import 'package:flutter_yishop/model/ProductContentModel.dart';
import 'package:flutter_yishop/pages/product/product_content/CartNum.dart';
import 'package:flutter_yishop/provider/Cart.dart';
import 'package:flutter_yishop/services/BuyServices.dart';
import 'package:flutter_yishop/services/CartServices.dart';
import 'package:flutter_yishop/services/UserService.dart';
import 'package:flutter_yishop/utils/screen/ScreenAdapter.dart';
import 'package:flutter_yishop/utils/toast_util.dart';
import 'package:flutter_yishop/widget/JDButton.dart';
import 'package:provider/provider.dart';

class TabProductPage extends StatefulWidget {
  final List _productContentList;

  TabProductPage(this._productContentList, {Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _TabProductPageState();
  }
}

class _TabProductPageState extends State<TabProductPage>
    with AutomaticKeepAliveClientMixin {
  ProductContentitem _productContent;

  List _attr = [];

  List<AttrStateModel> _attrStateModelList = [];

  String _selectedValue;

  var actionEventBus;

  var cartProvider;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._productContent = widget._productContentList[0];
    this._attr = this._productContent.attr;
    List<Attr> aattr = this._productContent.attr;
    // aattr.forEach((element) {
    //   print('attrList:${element.toJson()}');
    // });

    _initAttr();

    actionEventBus = eventBus.on<ProductContentEvent>().listen((event) {
      this._attrBottomSheet();
    });
  }

  //初始化Attr 格式化数据
  // _initAttr(){
  //
  //   for(var i = 0;i<this._attr.length;i++){
  //     List<AttrState> attrStateList = [];
  //     for(var j = 0;j<this._attr[i].list.length;j++){
  //       if(j == 0){
  //         attrStateList.add(AttrState(this._attr[i].list[j], true));
  //       }else{
  //         attrStateList.add(AttrState(this._attr[i].list[j], false));
  //       }
  //     }
  //     _attrStateModelList.add(AttrStateModel(this._attr[i].cate, attrStateList));
  //   }
  //
  //  print('attrStateModelList:${_attrStateModelList.toString()}');
  // }

  _initAttr() {
    var attr = this._attr;
    for (var i = 0; i < attr.length; i++) {
      for (var j = 0; j < attr[i].list.length; j++) {
        if (j == 0) {
          attr[i].attrList.add({"title": attr[i].list[j], "checked": true});
        } else {
          attr[i].attrList.add({"title": attr[i].list[j], "checked": false});
        }
      }
    }

    _getSelectedAttrValue();
  }

  //获取选中的值
  _getSelectedAttrValue() {
    var _list = this._attr;
    List tempAttr = [];
    for (var i = 0; i < _list.length; i++) {
      for (var j = 0; j < _list[i].attrList.length; j++) {
        if (_list[i].attrList[j]["checked"] == true) {
          tempAttr.add(_list[i].attrList[j]["title"]);
        }
      }
    }

    setState(() {
      this._selectedValue = tempAttr.join(',');
      //给筛选属性赋值
      this._productContent.selectedAttr = this._selectedValue;
    });
  }

  //改变属性值
  _changeAttr(cate, title, setBottomState) {
    var attr = this._attr;
    for (var i = 0; i < attr.length; i++) {
      if (attr[i].cate == cate) {
        for (var j = 0; j < attr[i].attrList.length; j++) {
          if (title == attr[i].attrList[j]["title"]) {
            attr[i].attrList[j]["checked"] = true;
          } else {
            attr[i].attrList[j]["checked"] = false;
          }
        }
      }
    }

    setBottomState(() {
      //注意：改变showModelBottomSheet里面的数据 来源于StatefulBuilder
      this._attr = attr;
    });
    _getSelectedAttrValue();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenAdapter.init(context);
    cartProvider = Provider.of<Cart>(context);
    //处理图片
    String pic = Config.url + this._productContent.pic;
    pic = pic.replaceAll('\\', '/');
    return Container(
      child: ListView(
        children: [
          AspectRatio(
            aspectRatio: 16 / 9,
            child: Image.network("$pic", fit: BoxFit.cover),
          ),
          //标题
          Container(
            margin: EdgeInsets.only(
                left: ScreenAdapter.width(15),
                right: ScreenAdapter.width(15),
                top: ScreenAdapter.height(15)),
            child: Text(
              "${this._productContent.title}",
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenAdapter.size(36)),
            ),
          ),
          Container(
              padding: EdgeInsets.only(
                top: ScreenAdapter.height(10),
                left: ScreenAdapter.width(18),
                right: ScreenAdapter.width(18),
              ),
              child: Text("${this._productContent.subTitle}",
                  style: TextStyle(
                      color: Colors.black54,
                      fontSize: ScreenAdapter.size(28)))),
          //价格
          Container(
            padding: EdgeInsets.only(
              top: ScreenAdapter.height(10),
              left: ScreenAdapter.width(18),
              right: ScreenAdapter.width(18),
            ),
            child: Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Row(
                    children: <Widget>[
                      Text("特价: "),
                      Text("${this._productContent.price}",
                          style: TextStyle(
                              color: Colors.red,
                              fontSize: ScreenAdapter.size(46))),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      Text("原价: "),
                      Text("${this._productContent.oldPrice}",
                          style: TextStyle(
                              color: Colors.black38,
                              fontSize: ScreenAdapter.size(28),
                              decoration: TextDecoration.lineThrough)),
                    ],
                  ),
                )
              ],
            ),
          ),
          //筛选
          this._attr.length > 0
              ? GestureDetector(
                  child: Container(
                    padding: EdgeInsets.only(
                      top: ScreenAdapter.height(10),
                      left: ScreenAdapter.width(18),
                      right: ScreenAdapter.width(18),
                    ),
                    height: ScreenAdapter.height(80),
                    child: Row(
                      children: <Widget>[
                        Text("已选: ",
                            style: TextStyle(fontWeight: FontWeight.bold)),
                        Text("${this._selectedValue}")
                      ],
                    ),
                  ),
                  onTap: () {
                    _attrBottomSheet();
                  },
                )
              : Text(""),
          Divider(),
          Container(
            padding: EdgeInsets.only(
              left: ScreenAdapter.width(18),
              right: ScreenAdapter.width(18),
            ),
            height: ScreenAdapter.height(80),
            child: Row(
              children: <Widget>[
                Text("运费: ", style: TextStyle(fontWeight: FontWeight.bold)),
                Text("免运费")
              ],
            ),
          ),
          Divider(),
        ],
      ),
    );
  }

  _attrBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return StatefulBuilder(
              builder: (BuildContext context, setBottomState) {
            return GestureDetector(
              //解决点击消失问题
              onTap: () {
                return false;
              },
              child: Stack(
                children: [
                  Container(
                    padding: EdgeInsets.all(ScreenAdapter.width(20)),
                    margin: EdgeInsets.only(bottom: ScreenAdapter.height(100)),
                    child: ListView(
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: _getAttrWidget(setBottomState),
                        ),
                        Divider(),
                        Container(
                          margin: EdgeInsets.only(top: 10),
                          height: ScreenAdapter.height(80),
                          child: GestureDetector(
                            child: Row(
                              children: [
                                Text("数量: ",
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold)),
                                SizedBox(width: 10),
                                CartNum(this._productContent)
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    width: ScreenAdapter.width(750),
                    height: ScreenAdapter.height(100),
                    child: Row(
                      children: [
                        Expanded(
                            flex: 1,
                            child: Container(
                              margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
                              child: JdButton(
                                color: Colors.red,
                                text: "加入购物车",
                                cb: () async {
                                  await CartServices.addCart(
                                      this._productContent);
                                  Navigator.of(context).pop();
                                  cartProvider.updateCartList();
                                  ToastUtil.showToasts("添加成功");
                                },
                              ),
                            )),
                        Expanded(
                          flex: 1,
                          child: Container(
                              margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                              child: JdButton(
                                color: Color.fromRGBO(255, 165, 0, 0.9),
                                text: "立即购买",
                                cb: () {
                                  if(UserService.getUserLoginState()==true){
                                    BuyServices.add(this._productContent);
                                    Navigator.of(context).pop();
                                    Navigator.pushNamed(context, Constants.CHECKOUT,
                                        arguments: {
                                          "routes":Constants.CHECKOUT,
                                        });
                                  }else{
                                    Navigator.of(context).pushNamed(Constants.LOGIN);
                                  }
                                },
                              )),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          });
        });
  }

  List<Widget> _getAttrWidget(setBottomState) {
    List<Widget> attrList = [];
    this._attr.forEach((attrItem) {
      attrList.add(Wrap(
        children: [
          Container(
            width: ScreenAdapter.width(120),
            child: Padding(
              padding: EdgeInsets.only(top: ScreenAdapter.height(10)),
              child: Text(
                "${attrItem.cate}",
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
          ),
          Row(
            children: [
              Expanded(
                // width: ScreenAdapter.width(610),
                flex: 1,
                child: Wrap(
                  children: _getAttrItemWidget(attrItem, setBottomState),
                ),
              ),
            ],
          ),
        ],
      ));
    });
    return attrList;
  }

  List<Widget> _getAttrItemWidget(attrItem, setBottomState) {
    List<Widget> attrItemList = [];
    attrItem.attrList.forEach((item) {
      attrItemList.add(Container(
        margin: EdgeInsets.all(5),
        child: GestureDetector(
          child: Chip(
            label: Text(
              "${item["title"]}",
              style: TextStyle(
                color: item["checked"] ? Colors.white : null,
              ),
            ),
            padding: EdgeInsets.all(5),
            backgroundColor: item["checked"] ? Colors.redAccent : null,
          ),
          onTap: () {
            _changeAttr(attrItem.cate, item["title"], setBottomState);
          },
        ),
      ));
    });
    return attrItemList;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    actionEventBus.cancel();
  }
}
